/**
 * 
 */
package br.webcrawler.activities.webcrawler;

/**
 * @author Gerson Groth
 *
 */
import java.util.ArrayList;
import java.util.List;
import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.ui.ExpectedCondition;
import org.openqa.selenium.support.ui.WebDriverWait;

public class Example {
	public static void main2(String[] args) {

		// Selenium selenium = new DefaultSelenium("localhost", 4444,
		// "*iexplore", "http://www.google.com");

		// selenium.start();

		// Create a new instance of the html unit driver
		// Notice that the remainder of the code relies on the interface,
		// not the implementation.
		WebDriver driver = new FirefoxDriver();

		// And now use this to visit Google
		driver.get("https://connect.garmin.com/signin");

		// Find the text input element by its name
		WebElement login = driver
				.findElement(By.id("login:loginUsernameField"));
		WebElement pass = driver.findElement(By.id("login:password"));
		WebElement button = driver.findElement(By.id("login:signInButton"));

		login.sendKeys("gersongroth");
		pass.sendKeys("groth2013");
		button.click();

		//
		// // Enter something to search for
		// element.sendKeys("Cheese!");
		//
		// // Now submit the form. WebDriver will find the form for us from the
		// element
		// element.submit();

		// Check the title of the page
		System.out.println("1111 Page title: " + driver.getTitle());
		System.err.println("\n\n\n");

		// System.err.println(driver.getPageSource());

		driver.get("http://connect.garmin.com/explore");
		// driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);

		WebDriverWait wait = new WebDriverWait(driver, 20);

		WebElement myDynamicElement;

		try {
			myDynamicElement = wait.until(new ExpectedCondition<WebElement>() {

				public WebElement apply(WebDriver d) {
					WebElement element = d.findElement(By
							.id("_viewRoot:status.start"));
					if (element == null)
						return null;
					else {
						if (element.isDisplayed())
							return element;
						else
							return null;
					}
				}
			});
		} catch (Exception e) {
			System.err.println("1");
		}
		System.out.println("\n\n\n\nTeste\n\n\n\n");
		try {
			myDynamicElement = wait.until(new ExpectedCondition<WebElement>() {

				public WebElement apply(WebDriver d) {
					WebElement element = d.findElement(By
							.id("_viewRoot:status.start"));
					if (element == null)
						return null;
					else {
						if (!element.isDisplayed())
							return element;
						else
							return null;
					}
				}
			});
		} catch (Exception e) {
			System.err.println("2");
		}

		WebElement explore = driver.findElement(By
				.id("exploreSearchForm:location"));
		WebElement timePeriod = driver.findElement(By
				.id("exploreSearchForm:timePeriodSelect"));
		WebElement showFilters = driver.findElement(By.id("showFilters"))
				.findElements(By.linkText("Show Filters")).get(0);
		WebElement search = driver.findElement(By.id("searchButton"));
		WebElement startDate = driver.findElement(By
				.id("exploreSearchForm:startDateCalendarInputDate"));
		WebElement endDate = driver.findElement(By
				.id("exploreSearchForm:endDateCalendarInputDate"));
		WebElement startDistance = driver.findElement(By
				.id("exploreSearchForm:activitySummarySumDistance-min"));
		WebElement endDistance = driver.findElement(By
				.id("exploreSearchForm:activitySummarySumDistance-max"));
		WebElement activityType = driver.findElement(By
				.id("exploreSearchForm:activityType"));

		// Wait<WebDriver> wait2 = new WebDriverWait(driver, 20);
		// WebElement element2 =
		// wait2.until(visibilityOfElementLocated(By.className("rich-datascr-button")));

		showFilters.click();

		explore.clear();
		timePeriod.sendKeys("customTimestamp");
		explore.sendKeys("São Paulo");
		activityType.sendKeys("running");

		JavascriptExecutor js = (JavascriptExecutor) driver;
		js.executeScript(
				"document.getElementById('exploreSearchForm:startDateCalendarInputDate').removeAttribute('readonly');",
				"");
		js.executeScript(
				"document.getElementById('exploreSearchForm:endDateCalendarInputDate').removeAttribute('readonly');",
				"");
		startDate.sendKeys("12/31/2012");
		endDate.sendKeys("12/31/2012");
		startDistance.sendKeys("13");
		endDistance.sendKeys("17");
		search.click();

		int pagina = 1;

		WebElement next = null;
		ArrayList<String> corridas = new ArrayList<String>();
		do {
			System.out.println("Iniciando página " + pagina);
			try {
				myDynamicElement = wait
						.until(new ExpectedCondition<WebElement>() {

							public WebElement apply(WebDriver d) {
								WebElement element = d.findElement(By
										.id("_viewRoot:status.start"));
								if (element == null)
									return null;
								else {
									if (element.isDisplayed())
										return element;
									else
										return null;
								}
							}
						});
			} catch (Exception e) {
				System.err.println("3");
			}

			try {
				myDynamicElement = wait
						.until(new ExpectedCondition<WebElement>() {
							public WebElement apply(WebDriver d) {
								WebElement element = d.findElement(By
										.id("_viewRoot:status.start"));
								if (element == null)
									return null;
								else {
									if (!element.isDisplayed())
										return element;
									else
										return null;
								}
							}
						});
			} catch (Exception e) {
				System.err.println("4");
			}

			List<WebElement> elements = driver.findElements(By
					.className("rich-datascr-button"));
			for (WebElement e : elements) {
				if (e.getText().equals("»")) {
					next = e;
					break;
				}
			}
			if (next == null) {
				System.err.println("Next null");
				// break;
			}

			WebElement paginaAtual = driver.findElement(By
					.className("rich-datascr-act"));

			System.out.println("Página " + paginaAtual.getText());

			System.out.println(next.isEnabled());

			// WebElement nextPage =
			// driver.findElements(By.className("rich-datascr-inact")).get(Integer.parseInt(paginaAtual.getText()));

			if (next.getAttribute("class")
					.contains("rich-datascr-button-dsbld")) {
				System.err.println("terminou");
			}

			System.out.println("Listando atividades");

			List<WebElement> tableRows = driver.findElements(By
					.className("rich-table-row"));

			for (WebElement e : tableRows) {
				WebElement resultsEntry = e.findElement(By
						.className("resultsEntry"));
				WebElement resultsTitle = resultsEntry.findElement(By
						.className("resultsTitle"));
				WebElement a = resultsTitle.findElement(By.tagName("a"));
				String[] activity = a.getAttribute("href").split("/");
				System.out.println("Activity " + activity[activity.length - 1]);
				// System.out.println(a.getAttribute("title"));
				System.out.println(a.getText());

				corridas.add(a.getAttribute("href"));
			}

			pagina++;
			next.click();
		} while (next != null
				&& !(next.getAttribute("class")
						.contains("rich-datascr-button-dsbld")));

		// resultsTitle

		// element2 =
		// wait2.until(visibilityOfElementLocated(By.className("rich-datascr-button")));

		// driver.get("http://connect.garmin.com/activity/137669024");
		//
		//
		// System.out.println("Page title is: " + driver.getTitle());
		// System.err.println(driver.getPageSource());
		//
		// List<WebElement> elements =
		// driver.findElements(By.className("resultsTitle"));
		//
		// for(WebElement e : elements){
		// System.out.println(e.getText());
		// }

		// WebElement element =
		// driver.findElement(By.id("_viewRoot:status.start"));
		//
		// // System.out.println(element.isDisplayed());
		// // System.out.println(element.isEnabled());
		//
		//
		//
		// wait = new WebDriverWait(driver, 120);
		// try{
		// myDynamicElement = wait
		// .until(new ExpectedCondition<WebElement>(){
		// @Override
		// public WebElement apply(WebDriver d) {
		// WebElement element = d.findElement(By.id("_teste"));
		// if(element == null) return null;
		// else{
		// if(!element.isDisplayed()) return element;
		// else return null;
		// }
		// }});
		// }catch(Exception e){ System.err.println("4");}

		// System.err.println(driver.getPageSource());
		// rich-datascr-button-dsbld rich-datascr-button »

	}

	public static ExpectedCondition<WebElement> visibilityOfElementLocated(
			final By by) {
		return new ExpectedCondition<WebElement>() {
			public WebElement apply(WebDriver driver) {
				WebElement element = driver.findElement(by);
				return element.isDisplayed() ? element : null;
			}
		};
	}
}